package algorithm.leetcode;

/**
 * @program: util
 * @description:
 * 1234 + 56789
 * 存储
 * 4->3->2->1 + 9->8->7->6->5
 * @author: zhouliangliang
 * @create: 2021-03-30 17:15
 **/
public class AddNumUseList {

    private ListNode  solve(ListNode l1, ListNode l2) {
        ListNode head =  null;
        ListNode tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int v1 = l1 == null ? 0 : l1.val;
            int v2 = l2 == null ? 0 : l2.val;
            int add = (v1 + v2 + carry) % 10; //和
            carry = (v1 + v2 + carry) / 10; //进位
            if(head == null) {
                head = tail = new ListNode(add);
            } else {
                tail.next = new ListNode(add);
                tail = tail.next;
            }

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if(carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }

    public static void main(String []args) {
        ListNode l1 = new ListNode(9,new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))));
        ListNode l2 = new ListNode(9,new ListNode(9, new ListNode(9)));
        ListNode head = new AddNumUseList().solve(l1, l2);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }

        System.out.println(99999 + 999);
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
